package com.jingan.nursinghome.regulatory.separate;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jingan.nursinghome.regulatory.MainActivity;
import com.jingan.nursinghome.regulatory.R;
import com.jingan.nursinghome.regulatory.data.MicrometerTable;
import com.jingan.nursinghome.regulatory.dialog.micrometertable.QianmiDialog;
import com.jingan.nursinghome.regulatory.separate.bean.CreateMic;
import com.jingan.nursinghome.regulatory.view.BitmapsView;
import com.jingan.nursinghome.regulatory.view.MyActionBar;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.android.support.v7.lib.sin.crown.base.BaseActivity;
import cn.android.support.v7.lib.sin.crown.base.BaseDialog;
import cn.android.support.v7.lib.sin.crown.base.BaseListenner;
import cn.android.support.v7.lib.sin.crown.base.BasePhotoActivity;
import cn.android.support.v7.lib.sin.crown.base.BasePhotoListenner;
import cn.android.support.v7.lib.sin.crown.dialog.AlertDialog;
import cn.android.support.v7.lib.sin.crown.dialog.PhotoDialog;
import cn.android.support.v7.lib.sin.crown.kotlin.common.Toast;
import cn.android.support.v7.lib.sin.crown.utils.AssetsUtils;
import cn.android.support.v7.lib.sin.crown.utils.NumberUtils;
import cn.android.support.v7.lib.sin.crown.utils.ProportionUtils;
import cn.android.support.v7.lib.sin.crown.utils.TimeUtils;
import cn.android.support.v7.lib.sin.crown.utils.ToastUtils;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;

/**
 * 千分表上传界面
 * Created by 彭治铭 on 2017/10/19.
 */

public class SeparateUploadDailog extends BaseDialog {


    public SeparateUploadDailog(BaseActivity baseActivity) {
        init(baseActivity, R.layout.dialog_micrometertablleos_commit, false);
        window.setWindowAnimations(cn.android.support.v7.lib.sin.crown.R.style.crown_window_right);
        initUI();
        //adapterUI();
    }


    private static SeparateUploadDailog commitDailog;

    static String spid;

    static SeparateDialog mSeparateDialog;

    public static SeparateUploadDailog getInstance(BaseActivity baseActivity, SeparateDialog separateDialog, String pid) {
        spid = pid;
        mSeparateDialog = separateDialog;
        if (isfinish(baseActivity, commitDailog)) {
            commitDailog = new SeparateUploadDailog(baseActivity);
        }
        return commitDailog;
    }

    MyActionBar myActionBar;
    TextView txt_hostory, txt_select, txt_next;

    TextView txt_hdfs2;//得分
    TextView txt_hdfs4;//得分率
    TextView txt_xunjian;//巡检表类型
    TextView txt_jigou;//巡检机构
    TextView txt_time;//巡检时间
    TextView txt_goutou;//主要沟通人员
    EditText txt_beizhu2;//备注
    TextView txt_name;//套题名称

    Button btn_img;//上传照片
    Button btn_qianmi;//签名

    BitmapsView bitmapsView;//位图显示

    public void initUI() {
        myActionBar = (MyActionBar) findViewById(R.id.MyActionBar);
        myActionBar.setLeftBimapAndTitle(null, "评分结果");
        myActionBar.setBaseListennerLeft(new BaseListenner() {
            @Override
            public void onResult(Object result) {
                onBack();
            }
        });
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getAction() == KeyEvent.ACTION_DOWN) {
                    onBack();
                    return true;//记得返回true。表示已经处理。
                }
                return false;//返回键以外交给系统自行处理。不可以屏蔽，不然输入法键盘的按键可能无效。如删除键
            }
        });
        txt_name = (TextView) findViewById(R.id.txt_name);
        txt_hostory = (TextView) findViewById(R.id.txt_hostory);
        txt_select = (TextView) findViewById(R.id.txt_select);
        txt_next = (TextView) findViewById(R.id.txt_next);
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.txt_hostory://上一项
                        dismiss();
                        break;
                    case R.id.txt_select://选题
                        break;
                    case R.id.txt_next://提交
                        //fixme 上传提交。========================================================================================================================================================================
                        if ((QMbitmap == null || QMbitmap.isRecycled())) {//组长，才要签名
                            baseActivity.SnackbarMake("签名不能为空!", true, findViewById(R.id.dialog_micrometertableos_constraintLayout));
                            break;
                        }
                        //组长 提交
                        Map<String, String> map = new HashMap<>();
                        Map<String, File> fileMap = new HashMap<>();
                        File file = AssetsUtils.getInstance().saveBitmap(QMbitmap, baseActivity.getApplicationContext().getFilesDir().getAbsolutePath(), MicrometerTable.getInstance().getUser().getId() + System.currentTimeMillis() + ".png");
                        //Log.e("test", "文件:\t" + file.getName() + "\t大小:\t" + file.length());
                        fileMap.put("signature", file);//签名,组长才要签名
                        map.put("pid", spid);
                        //多图片资源
                        for (int i = 0; i < files.size(); i++) {
                            if (i == 0) {
                                fileMap.put("polling_img_yi", files.get(i));
                            }
                            if (i == 1) {
                                fileMap.put("polling_img_er", files.get(i));
                            }
                            if (i == 2) {
                                fileMap.put("polling_img_san", files.get(i));
                            }
                            if (i == 3) {
                                fileMap.put("polling_img_si", files.get(i));
                            }
                            if (i == 4) {
                                fileMap.put("polling_img_wu", files.get(i));
                            }
                        }

                        //Log.e("test", "巡检人ID:\t" + Uri.INSTANCE.getUser().getId());
                        String t = TimeUtils.getInstance().getAbsoluteTime(" HH:mm:ss");
                        //map.put("routing_inspection_time", CreateSeparateDailog.time + t);//巡检时间
                        //map.put("oid", MicrometerTable.getInstance().getJlyID(CreateSeparateDailog.jlyName));//敬老院机构ID

                        //主要沟通人员ID
//                        String[] lids = CreateSeparateDailog.names.split("、");
//                        String lids2 = "";
//                        for (int i = 0; i < lids.length; i++) {
//                            String id = MicrometerTable.getInstance().getLinkupID(lids[i]);
//                            if (i == 0) {
//                                lids2 = id;
//                            } else {
//                                lids2 = lids2 + "," + id;
//                            }
//                        }
//                        map.put("lid", lids2);//主要沟通人员id
                        map.put("remark", txt_beizhu2.getText().toString());//备注
//                        map.put("otherpeople", CreateSeparateDailog.other);//其他
//                        map.put("stname", CreateSeparateDailog.rid);//套题名称

                        Uri.INSTANCE.submitTup(activity, map, fileMap, new Function1<String, Unit>() {
                            @Override
                            public Unit invoke(String s) {
                                //提交 fixme ================================================================================================================================================================
                                Uri.INSTANCE.upload(activity, spid, new Function1<String, Unit>() {
                                    @Override
                                    public Unit invoke(String s) {
                                        dismiss();
                                        Toast.INSTANCE.show(s, null);
                                        return null;
                                    }
                                });

                                return null;
                            }
                        });
                        break;
                }
            }
        };
        txt_hostory.setOnClickListener(onClickListener);
        txt_select.setOnClickListener(onClickListener);
        txt_next.setOnClickListener(onClickListener);

        txt_hdfs2 = (TextView)

                findViewById(R.id.txt_hdfs2);

        txt_hdfs4 = (TextView)

                findViewById(R.id.txt_hdfs4);

        txt_xunjian = (TextView)

                findViewById(R.id.txt_xunjian);

        txt_jigou = (TextView)

                findViewById(R.id.txt_jigou);

        txt_time = (TextView)

                findViewById(R.id.txt_time);

        txt_goutou = (TextView)

                findViewById(R.id.txt_goutou);

        txt_beizhu2 = (EditText)

                findViewById(R.id.txt_beizhu2);

        bitmapsView = (BitmapsView)

                findViewById(R.id.bitmaps);

        btn_img = (Button)

                findViewById(R.id.btn_img);
        btn_img.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                //上传照片
                if (BasePhotoActivity.SnakbarView == null) {
                    BasePhotoActivity.SnakbarView = btn_img;
                }
                PhotoDialog.getInstance(MainActivity.mainActivity, true, new BasePhotoListenner() {
                    @Override
                    public void onSuccess(File file, Bitmap bitmap) {
                        if (bitmaps.size() < 5) {
                            bitmaps.add(bitmap);
                            files.add(file);
                        } else {
                            bitmaps.remove(4);
                            bitmaps.add(4, bitmap);
                            files.add(4, file);
                        }
                        bitmapsView.setBitmaps(bitmaps);
                    }
                });
            }
        });

        btn_qianmi = (Button)

                findViewById(R.id.btn_qianmi);
        btn_qianmi.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                //签名
                QianmiDialog.getInstance(baseActivity, new BaseListenner<Bitmap>() {
                    @Override
                    public void onResult(Bitmap result) {
                        QMbitmap = result;
                    }
                });
            }
        });

    }

    public static Bitmap QMbitmap;//签名位图

    public static List<Bitmap> bitmaps = new ArrayList<>();//位图数组
    public static List<File> files = new ArrayList<>();//位图文件数组

    public void adapterUI() {
        ProportionUtils.getInstance().adapterScreen(baseActivity, findViewById(R.id.dialog_micrometertableos_constraintLayout));
        ProportionUtils.getInstance().adapterTextView(txt_hostory);
        ProportionUtils.getInstance().adapterTextView(txt_select);
        ProportionUtils.getInstance().adapterTextView(txt_next);
        ProportionUtils.getInstance().adapterTextView((TextView) findViewById(R.id.txt_hdfs));
        ProportionUtils.getInstance().adapterTextView((TextView) findViewById(R.id.txt_beizhu));
        ProportionUtils.getInstance().adapterTextView((TextView) findViewById(R.id.txt_btn_img));
        ProportionUtils.getInstance().adapterTextView(txt_hdfs2);
        ProportionUtils.getInstance().adapterTextView(txt_xunjian);
        ProportionUtils.getInstance().adapterTextView(txt_jigou);
        ProportionUtils.getInstance().adapterTextView(txt_time);
        ProportionUtils.getInstance().adapterTextView(txt_goutou);
        ProportionUtils.getInstance().adapterTextView(txt_beizhu2);

        ProportionUtils.getInstance().adapterButton(btn_img);
        ProportionUtils.getInstance().adapterButton(btn_qianmi);

        ProportionUtils.getInstance().adapterTextView((TextView) findViewById(R.id.txt_hdfs3));
        ProportionUtils.getInstance().adapterTextView(txt_hdfs4);
        ProportionUtils.getInstance().adapterTextView(txt_name);
    }


    @Override
    protected void listener() {//FIXME ===================================================================================================================================================================================

        findViewById(R.id.txt_zhengai).setVisibility(View.INVISIBLE);//整改项
        findViewById(R.id.txt_select).setVisibility(View.GONE);//选题

        Uri.INSTANCE.Fkpingfen(activity, spid, new BaseListenner<CreateMic>() {
            @Override
            public void onResult(CreateMic result) {

                txt_jigou.setText("巡检机构：" + result.getOname());
                txt_time.setText("巡检时间：" + result.getRouting_inspection_time());
                txt_goutou.setText("主要沟通人员:\t" + result.getLname());
                txt_name.setText("套题名称:\t" + result.getStname());//套题名称

                txt_hdfs2.setText(result.getZondeifen() + "分/" + result.getTotal_score() + "分");
                txt_hdfs4.setText(result.getDeifenlv());//得分率

            }
        });

//        if (MicrometerTable.getInstance().getUser().getUtype().trim().equals("4")) {
//            isZU = true;//组长
//            txt_beizhu2.setVisibility(View.VISIBLE);
//            btn_img.setVisibility(View.VISIBLE);
//            findViewById(R.id.txt_btn_img).setVisibility(View.VISIBLE);
//            btn_qianmi.setVisibility(View.VISIBLE);
//            findViewById(R.id.txt_beizhu).setVisibility(View.VISIBLE);
//
//            txt_jigou.setText("巡检机构：" + CreateSeparateDailog.jlyName);
//            txt_time.setText("巡检时间：" + CreateSeparateDailog.time);
//            txt_goutou.setText("主要沟通人员:\t" + CreateSeparateDailog.names);
//            txt_name.setText("套题名称:\t" + CreateSeparateDailog.rid);//套题名称
//
//        } else {
//            isZU = false;//组员
//            txt_beizhu2.setVisibility(View.INVISIBLE);
//            btn_img.setVisibility(View.INVISIBLE);
//            findViewById(R.id.txt_btn_img).setVisibility(View.INVISIBLE);
//            btn_qianmi.setVisibility(View.INVISIBLE);
//            findViewById(R.id.txt_beizhu).setVisibility(View.INVISIBLE);
//
//        }
        txt_xunjian.setText("巡检表类型：千分表");

        bitmapsView.setBaseListener(new BaseListenner<Integer>() {
            @Override
            public void onResult(Integer result) {
                bitmaps.remove((int) result);
                files.remove((int) result);
                bitmapsView.setBitmaps(bitmaps);
            }
        });
        if (bitmaps.size() > 0) {
            bitmapsView.setBitmaps(bitmaps);
        }
    }

    AlertDialog alertDialog;

    void onBack() {
        alertDialog = AlertDialog.getInstance(baseActivity, false, false).setTitle("提示").setMession("是否放弃本次上传?");
        alertDialog.setPositive("是", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                alertDialog.dismiss();
            }
        });
    }

    @Override
    protected void recycleView() {
        if (QMbitmap != null) {
            QianmiDialog.clear();
            if (!QMbitmap.isRecycled()) {
                QMbitmap.recycle();
            }
            QMbitmap = null;
        }
        for (int i = 0; i < bitmaps.size(); i++) {
            if (bitmaps.get(i) != null && !bitmaps.get(i).isRecycled()) {
                bitmaps.get(i).recycle();
            }
        }
        bitmaps.clear();
        files.clear();

        if (mSeparateDialog != null) {
            mSeparateDialog.listener();//首页刷新
            mSeparateDialog = null;
        }
    }

}
